﻿using IPlugin;
using IPlugin.Attributes;
using NLog;
using SimpleTCP;

namespace DeviceTcpClient
{
    [DriverSupported("MockTcpDriver")]
    public class MockTcpDriver : IDriver
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();

        public bool IsConnected => _client != null && _client.TcpClient != null && _client.TcpClient.Connected;

        private SimpleTcpClient _client;
        private byte[] _latestRcvData;

        private readonly string _device;

        #region 配置参数

        [ConfigParameter("设备Id")]
        public int DeviceId { get; set; }

        [ConfigParameter("IP地址")]
        public string IpAddress { get; set; } = "127.0.0.1";

        [ConfigParameter("端口号")]
        public int Port { get; set; } = 6666;


        [ConfigParameter("超时时间ms")]
        public int TimeOut { get; set; } = 300;
        [ConfigParameter("最小通讯周期ms")]
        public int MinPeriod { get; set; } = 3000;

        #endregion

        public MockTcpDriver(string device)
        {
            _device = device;
        }


        public bool Close()
        {
            try
            {
                if (_client != null)
                {
                    _client.DataReceived -= Client_DataReceived;
                    //断开连接
                    _client?.Disconnect();
                }

                return !IsConnected;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool Connect()
        {
            try
            {
                //进行连接
                _client = new SimpleTcpClient().Connect(IpAddress, Port);
                _client.DataReceived += Client_DataReceived;
            }
            catch (Exception)
            {
                return false;
            }

            return IsConnected;
        }

        private void Client_DataReceived(object sender, Message e)
        {
            if (e.Data.Length == 8 && e.Data[0] == 0x08)
                _latestRcvData = e.Data;
        }

        public DriverReturnValueModel Read(DriverAddressIoArgModel ioArg)
        {
            var ret = new DriverReturnValueModel { StatusType = EnumVariableStatus.Good };

            //连接正常则进行读取
            if (IsConnected)
            {
                try
                {
                    //发送请求
                    _client?.Write(ioArg.Address);
                    //等待恢复，这里可以优化
                    Thread.Sleep(TimeOut);
                    if (_latestRcvData == null)
                    {
                        ret.StatusType = EnumVariableStatus.Bad;
                        ret.Message = "没有收到数据";
                    }
                    else
                    {
                        ret.Value = _latestRcvData;
                        ret.StatusType = EnumVariableStatus.Good;
                    }
                }
                catch (Exception ex)
                {
                    ret.StatusType = EnumVariableStatus.Bad;
                    ret.Message = $"读取失败,{ex.Message}";
                }
            }
            else
            {
                ret.StatusType = EnumVariableStatus.Bad;
                ret.Message = "连接失败";
            }

            return ret;
        }

        public Task<RpcResponse> WriteAsync(string RequestId, string Method, DriverAddressIoArgModel ioArg)
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
